
// src/pages/VMList/VMList.tsx
import React, { useEffect, useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Select,
  Tag,
  Dropdown,
  Modal,
} from 'antd';
import type { MenuProps, TableColumnsType } from 'antd';
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  MoreOutlined,
  PlayCircleOutlined,
  PoweroffOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDomainStore } from '../../stores/domainStore';
import { usePolling } from '../../hooks/usePolling';
import type { Domain } from '../../api/types';

const { Search } = Input;

const VMList: React.FC = () => {
  const navigate = useNavigate();
  const {
    domains,
    fetchDomains,
    startDomain,
    shutdownDomain,
    deleteDomain,
    loading,
  } = useDomainStore();

  const [searchText, setSearchText] = useState('');
  const [stateFilter, setStateFilter] = useState<string | undefined>(undefined);
  const [refreshing, setRefreshing] = useState(false);

  useEffect(() => {
    fetchDomains();
  }, [fetchDomains]);

  // 自动刷新
  usePolling(fetchDomains, { interval: 5000 });

  // 手动刷新
  const handleRefresh = async () => {
    setRefreshing(true);
    await fetchDomains();
    setRefreshing(false);
  };

  // 过滤数据
  const filteredDomains = domains.filter((vm) => {
    const matchesSearch = vm.name.toLowerCase().includes(searchText.toLowerCase());
    const matchesState = !stateFilter || vm.state === stateFilter;
    return matchesSearch && matchesState;
  });

  // 操作菜单
  const getActionMenu = (vm: Domain): MenuProps['items'] => [
    {
      key: 'start',
      label: '启动',
      icon: <PlayCircleOutlined />,
      disabled: vm.state === 'running',
      onClick: () => startDomain(vm.name),
    },
    {
      key: 'shutdown',
      label: '关机',
      icon: <PoweroffOutlined />,
      disabled: vm.state !== 'running',
      onClick: () => shutdownDomain(vm.name),
    },
    {
      type: 'divider',
    },
    {
      key: 'delete',
      label: '删除',
      icon: <DeleteOutlined />,
      danger: true,
      onClick: () => {
        Modal.confirm({
          title: '确认删除',
          content: `确定要删除虚拟机 "${vm.name}" 吗？此操作不可恢复。`,
          okText: '删除',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => deleteDomain(vm.name),
        });
      },
    },
  ];

  // 表格列
  const columns: TableColumnsType<Domain> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      sorter: (a, b) => a.name.localeCompare(b.name),
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      render: (state: string) => {
        const colors: Record<string, string> = {
          running: 'success',
          shutoff: 'default',
          paused: 'warning',
          crashed: 'error',
        };
        return <Tag color={colors[state]}>{state}</Tag>;
      },
      filters: [
        { text: '运行中', value: 'running' },
        { text: '已关机', value: 'shutoff' },
        { text: '已暂停', value: 'paused' },
      ],
      onFilter: (value, record) => record.state === value,
    },
    {
      title: 'CPU',
      dataIndex: 'vcpus',
      key: 'vcpus',
      render: (vcpus: number) => `${vcpus} vCPU`,
      sorter: (a, b) => a.vcpus - b.vcpus,
    },
    {
      title: '内存',
      dataIndex: 'memory',
      key: 'memory',
      render: (memory: number) => `${(memory / 1024).toFixed(1)} GB`,
      sorter: (a, b) => a.memory - b.memory,
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            onClick={() => navigate(`/vms/${record.name}`)}
          >
            详情
          </Button>
          <Dropdown menu={{ items: getActionMenu(record) }} trigger={['click']}>
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card
        title="虚拟机列表"
        extra={
          <Space>
            <Search
              placeholder="搜索虚拟机"
              allowClear
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 200 }}
              prefix={<SearchOutlined />}
            />
            <Select
              placeholder="状态筛选"
              allowClear
              style={{ width: 120 }}
              value={stateFilter}
              onChange={setStateFilter}
            >
              <Select.Option value="running">运行中</Select.Option>
              <Select.Option value="shutoff">已关机</Select.Option>
              <Select.Option value="paused">已暂停</Select.Option>
            </Select>
            <Button
              icon={<ReloadOutlined spin={refreshing} />}
              onClick={handleRefresh}
            >
              刷新
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate('/create')}
            >
              新建虚拟机
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={filteredDomains}
          rowKey="uuid"
          loading={loading}
          pagination={{
            pageSize: 20,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          onRow={(record) => ({
            onClick: () => navigate(`/vms/${record.name}`),
            style: { cursor: 'pointer' },
          })}
        />
      </Card>
    </div>
  );
};

export default VMList;